package com.zcl.logic;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import com.netqin.netconnection.FileDownloadMgr;
import com.netqin.netconnection.FileDownloadMgrFactory;
import com.netqin.netconnection.FileDownloadTask;
import com.netqin.ui.share.sinaweibo.Weibo;
import com.zcl.bean.Task;
import com.zcl.bean.UserInfo;
import com.zcl.iweibo.IWeiboActivity;
import com.zcl.iweibo.WebViewActivity;
import com.zcl.protocol.APPProBase;
import com.zcl.protocol.APPProUser;
import com.zcl.protocol.APPProtocolInterface;
import com.zcl.utils.NqLog;
import com.zcl.utils.NqUtil;
import com.zcl.utils.Value;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class MainService extends Service implements Runnable {
	
	// 任务队列
	private static Queue<Task> tasks = new LinkedList<Task>();
	
	// 页面集合
	private static List<IWeiboActivity> activities = new ArrayList<IWeiboActivity>();
	
	// 是否运行
	private boolean isRun;
	
	// 新添加任务
	public static boolean newTask(Task t)
	{
		return tasks.offer(t);
	}
	
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Task.WEIBO_LOGIN:{
				IWeiboActivity activity = getActivityByName("LoginActivity");
				activity.refresh(msg);
			}
				break;
			case Task.PARSE_SUCCESS:{
				if (APPProtocolInterface.CMD01_GETUSERINFO == msg.arg1) {
					IWeiboActivity activity = getActivityByName("WebViewActivity");
					msg.arg2 = Task.REQUEST_USER_SUCCESS;
					activity.refresh(msg);
				}
			}
				break;
			case Task.PARSE_FAILED:{
				if (APPProtocolInterface.CMD01_GETUSERINFO == msg.arg1) {
					NqLog.d("error code:"+msg.arg2);
					msg.arg2 = Task.REQUEST_USER_FAILED;
					IWeiboActivity activity = getActivityByName("WebViewActivity");
					activity.refresh(msg);
				}
			}
				break;
			case Task.TAKEOUT_LOCAL_USERS:{
				IWeiboActivity activity = getActivityByName("LoginActivity");
				activity.refresh(msg);
			}
				break;
			case Task.REQUEST_NETWORK_HEADICON:{
				if (msg.obj instanceof FileDownloadTask) {
					FileDownloadTask downloadTask = (FileDownloadTask)msg.obj;
					if (downloadTask.getStatus() == FileDownloadTask.TaskStatusCode.Succeeded ) {
						UserInfoService infoService = new UserInfoService(getApplicationContext());
						UserInfo info = infoService.getUserInfoByUserId(String.valueOf(msg.arg1));
						if (info != null) {
							Bitmap bitmap = NqUtil.getBitmap(downloadTask.getFilePath(), -1, -1);
							infoService.updateUserInfo(info, NqUtil.bitmapConvertDrawable(getApplicationContext(), bitmap));
						}
					}else if (downloadTask.getStatus() == FileDownloadTask.TaskStatusCode.Failed) {
						NqLog.d("download img failed!");
					}
				}
			}
				break;
			default:
				break;
			}
		}
	};
	
	public static boolean addActivity(IWeiboActivity activity)
	{
		if (getActivityByName(activity.getClass().getName()) == null) {
			return activities.add(activity);
		}else {
			if(removeActivity(activity)){
				return activities.add(activity);
			}
		}
		return false;
	}
	
	public static boolean removeActivity(IWeiboActivity activity)
	{
		if (getActivityByName(activity.getClass().getName()) != null) {
			return activities.remove(activity);
		}
		return false;
	}
	
	private static IWeiboActivity getActivityByName(String activity) {
		if (activities.size() == 0) {
			return null;
		}
		for (int i = 0; i < activities.size(); i++) {
			if (activities.get(i).getClass().getName().indexOf(activity) != -1) {
				return activities.get(i);
			}
		}
		return null;
	}
	
	private void doTask(Task t)
	{
		switch (t.getTaskId()) {
		case Task.WEIBO_LOGIN:{
			Message message = handler.obtainMessage();
			message.what = Task.WEIBO_LOGIN;
			message.obj = "login success!";
			handler.sendMessage(message);
		}
			break;
		case Task.REQUEST_USER:{
			Activity activity = (Activity)getActivityByName("WebViewActivity");
			Weibo weibo = Weibo.getInstance();
			UserInfo info = new UserInfo();
			info.setToken(weibo.getAccessToken().getToken());
			info.setUserId(weibo.getUserID());
			APPProBase userProBase = new APPProUser(APPProtocolInterface.CMD01_GETUSERINFO, activity, info);
			WeiboService weiboService = new WeiboService((WebViewActivity)activity);
			weiboService.requestWeiboProtocol(handler, userProBase);
		}
			break;
		case Task.TAKEOUT_LOCAL_USERS:{
			Activity activity = (Activity)getActivityByName("LoginActivity");
			UserInfoService infoService = new UserInfoService(activity);
			List<UserInfo> users = infoService.findAllUsers();
			handler.sendMessage(handler.obtainMessage(Task.TAKEOUT_LOCAL_USERS, users));
		}
			break;
		case Task.REQUEST_NETWORK_HEADICON:{
			FileDownloadMgr fileDownloadMgr = FileDownloadMgrFactory.getInstance(getApplicationContext());
			Message msg = handler.obtainMessage();
			msg.what = Task.REQUEST_NETWORK_HEADICON;
			msg.arg1 = (Integer)t.getTaskParams().get(Value.REQUEST_HEAD_ICON_ID);
			String imgUrlPath = (String)t.getTaskParams().get(Value.REQUEST_HEAD_ICON_URLPATH);
			FileDownloadTask downloadTask = fileDownloadMgr.addFileDownloadTask(imgUrlPath, msg, handler);
			fileDownloadMgr.start(downloadTask);
		}
			break;
		default:
			break;
		}
		
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		isRun = true;
		Thread thread = new Thread(this);
		thread.start();
	}
	
	@Override
	public void run() {
		while (isRun) {
			if(!tasks.isEmpty()){
//				isRun = false;
//			}else {
				Task task = null;
				task = tasks.poll();
				if(task!=null)
				{
					doTask(task);
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}
